package com.gao.mq.controller;

import com.gao.mq.domain.MessageInfo;
import com.gao.mq.dto.ContentModel;
import com.gao.mq.dto.EmailContentModel;
import com.gao.mq.dto.SmsContentModel;
import com.gao.mq.service.MessageProducerService;
import com.gao.mq.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * 下单请求
 */
@RestController
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private MessageProducerService producerService;

    /**
     * 下单请求
     */
    @PostMapping(value = "orders")
    public String ordersProcess() {
        boolean isSuccess = ordersService.createOrders();
        // 如果订单创建成功，将短信消息添加到消息队列中
        if (isSuccess) {
            // 待发送的消息应该是订单交易返回的结果，这里简单处理
            MessageInfo messageInfo = new MessageInfo();
            Random random = new Random();
            int i = random.nextInt(10)*100000;
            String orderNo = "TXN" + i;
            String content = "您的订单"+ orderNo +"已于今天12:00交易成功！";
            Set<String> receiver = new HashSet<>();
            receiver.add("13676586961");
            SmsContentModel contentModel = new SmsContentModel();
            messageInfo.setReceiver(receiver);
            messageInfo.setTemplateCode("10001");
            contentModel.setContent(content);
            messageInfo.setContentModel(contentModel);
            // 发短信
            messageInfo.setMessageType(1);
            producerService.sendMessage(messageInfo);

            // 发邮件
            messageInfo.setMessageType(2);
            EmailContentModel emailContentModel = new EmailContentModel();
            emailContentModel.setTitle("订单交易通知");
            emailContentModel.setContent(content);
            messageInfo.setContentModel(emailContentModel);
            receiver.clear();
            receiver.add("1036026310@qq.com");
            messageInfo.setReceiver(receiver);
            producerService.sendMessage(messageInfo);
        }

        return "OK";
    }
}
